package cn.zebra.dev.member.module.member.service.impl;

import cn.zebra.dev.base.module.member.constant.MemberSexConstant;
import cn.zebra.dev.common.utils.StrUtils;
import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.ibatis.plus.utils.Query;
import cn.zebra.dev.member.module.member.dao.MemberDao;
import cn.zebra.dev.member.module.member.entity.MemberEntity;
import cn.zebra.dev.member.module.member.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 会员用户表(基础)
 *
 * @author runnable
 * @date 2019-08-29 17:33:26
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils<MemberEntity> queryPage(Map<String, Object> params) {
        Page<MemberEntity> page = new Query<MemberEntity>(params).getPage();
        page.setRecords(baseMapper.queryPage(page, params));
        return new PageUtils<>(page);
    }

    @Override
    public MemberEntity findMemberByPhone(String phone) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.apply("phone = {0}", phone);
        return getOne(wrapper);
    }

    @Override
    public Boolean updateMemberHeadPhoto(Long memberId, String imageUrl) {
        MemberEntity entity = new MemberEntity();
        entity.setMemberHeadImg(imageUrl);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberName(Long memberId, String newUsername) {
        MemberEntity entity = new MemberEntity();
        entity.setMemberName(newUsername);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberSex(Long memberId, Integer sex) {
        MemberEntity entity = new MemberEntity();
        entity.setSex(sex);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberAddress(Long memberId, String address) {
        UpdateWrapper<MemberEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("address", address);
        wrapper.apply("id = {0}", memberId);
        return update(wrapper);
    }

    @Override
    public Collection<MemberEntity> findListByMemberIds(Collection<Long> memberIds) {
        if (memberIds == null || memberIds.isEmpty()) {
            return new ArrayList<>(2);
        }
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", memberIds);
        return list(wrapper);
    }

    @Override
    public Long findByItemNum(Long memberId) {
        return baseMapper.findByItemNum(memberId);
    }

    @Override
    public Collection<MemberEntity> findAllMemberByMemberId(Long memberId) {
        return selectList("member_path LIKE CONCAT('%', {0}, '%') AND id != {0}", memberId);
    }

    /**
     * 根据用户名查找用户信息
     *
     * @param memberName 用户名
     * @return 用户对象
     */
    @Override
    public MemberEntity findByMemberName(String memberName) {
        return selectOne("member_name = {0}", memberName);
    }

    @Override
    public Boolean updateStatus(Long memberId, Integer status) {
        MemberEntity entity = new MemberEntity();
        entity.setStatus(status);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public MemberEntity findParentMemberByMemberId(Long memberId) {
        return baseMapper.findParentMemberByMemberId(memberId);
    }

    @Override
    public Collection<MemberEntity> findByTree(Long memberId) {
        return selectList("member_path LIKE CONCAT('%^', {0}, '^%')", memberId);
    }

    /**
     * 根据member_code查找用户
     *
     * @param memberCode 用户唯一码
     * @return 如果存在返回用户对象 如果不存在则返回null
     */
    @Override
    public MemberEntity findByMemberCode(String memberCode) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.apply("member_code = {0}", memberCode);
        return this.getOne(wrapper);
    }

    @Override
    public List<MemberEntity> findByIds(List<Long> memberIds) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", memberIds);
        return this.list(wrapper);
    }

    @Override
    public Boolean updateMemberPassword(Long memberId, String newPassword) {
        MemberEntity entity = new MemberEntity();
        entity.setPassword(newPassword);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberEmail(Long memberId, String newEmail) {
        MemberEntity entity = new MemberEntity();
        entity.setEmail(newEmail);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberPhone(Long memberId, String newPhone) {
        MemberEntity entity = new MemberEntity();
        entity.setPhone(newPhone);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberSecondaryPassword(Long memberId, String newSecondaryPassword) {
        MemberEntity entity = new MemberEntity();
        entity.setSecondaryPassword(newSecondaryPassword);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberSecondaryPassword(Long memberId, String secondarySale, String newSecondaryPassword) {
        MemberEntity entity = new MemberEntity();
        entity.setSecondarySalt(secondarySale);
        entity.setSecondaryPassword(newSecondaryPassword);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberPassword(String phone, String newPassword) {
        MemberEntity entity = new MemberEntity();
        entity.setPassword(newPassword);
        return update(entity, "phone = {0}", phone);
    }

    @Override
    public Integer countMemberByParentId(Long memberId) {
        return count("parent_id = {0}", memberId);
    }

    /**
     * 根据用户id统计直推人数(异步返回)
     *
     * @param memberId 用户id
     * @return 直推人数
     */
    @Override
    @Async
    public Future<MemberEntity> asyncCountMemberAndParentId(Long memberId) {
        Integer count = this.countMemberByParentId(memberId);
        MemberEntity entity = new MemberEntity();
        entity.setId(memberId);
        entity.setCount(count);
        return AsyncResult.forValue(entity);
    }

    @Override
    public List<MemberEntity> findIdAndMemberNameListByParentId(Long parentId) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id , member_name, member_level");
        wrapper.apply("parent_id = {0}", parentId);
        return list(wrapper);
    }

    @Override
    public List<MemberEntity> findIdAndMemberNameListByParentIdOfParentId(Long parentId) {
        return baseMapper.findIdAndMemberNameListByParentIdOfParentId(parentId);
    }

    @Override
    public Boolean updateMemberAge(Long memberId, Integer age) {
        MemberEntity entity = new MemberEntity();
        entity.setAge(age);
        return update(entity, "id = {0}", memberId);
    }

    @Override
    public MemberEntity findById(Long memberId) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.apply("id = {0}", memberId);
        return getOne(wrapper);
    }

    @Override
    public Boolean updateMemberLevel(Long memberId, Long memberLevel, Long newMemberLevel) {
        MemberEntity entity = new MemberEntity();
        entity.setMemberLevel(newMemberLevel);
        return update(entity, "id = {0} AND member_level = {1}", memberId, memberLevel);
    }

    @Override
    public Boolean saveMember(MemberEntity member) {
        if (member.getMemberType() == null) {
            member.setMemberType(0);
        }
        if (StrUtils.isBlank(member.getMemberName())) {
            member.setMemberName("");
        }
        if (StrUtils.isBlank(member.getMemberAccount())) {
            member.setMemberAccount("");
        }
        if (StrUtils.isBlank(member.getMemberHeadImg())) {
            member.setMemberHeadImg("");
        }
        if (member.getSex() == null) {
            member.setSex(MemberSexConstant.UNKNOWN);
        }
        if (member.getAge() == null) {
            member.setAge(0);
        }
        if (member.getParentId() == null) {
            member.setParentId(0L);
        }
        if (StrUtils.isBlank(member.getPhone())) {
            member.setPhone("");
        }
        if (StrUtils.isBlank(member.getEmail())) {
            member.setEmail("");
        }
        if (member.getMemberLevel() == null) {
            member.setMemberLevel(0L);
        }
        if (member.getStatus() == null) {
            member.setStatus(0);
        }
        if (member.getLevelExp() == null) {
            member.setLevelExp(0L);
        }
        member.setCreateTime(LocalDateTime.now());
        return save(member);
    }

    @Override
    public Boolean addMemberExp(Long memberId, Long addExp) {
        return baseMapper.addMemberExp(memberId, addExp) > 0;
    }

    @Override
    public Boolean updateMemberExp(Long memberId, Long exp, Long newExp) {
        UpdateWrapper<MemberEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("level_exp", newExp);
        wrapper.apply("id = {0} AND level_exp = {1}", memberId, exp);
        return update(wrapper);
    }

    @Override
    public Long findTeamNumById(Long memberId) {
        return baseMapper.findTeamNumById(memberId);
    }

    @Override
    public List<MemberEntity> findListByParentId(Long parentId) {
        return selectList("parent_id = {0}", parentId);
    }

    @Override
    public List<MemberEntity> findListByParentIdAndMemberLevel(Long parentId, Long levelId) {
        return selectList("parent_id = {0} AND member_level = {1}", parentId, levelId);
    }

    @Override
    public List<MemberEntity> findIdAndMemberNameListByParentIdOfParentIdAndLevelId(Long parentId, Long levelId) {
        return baseMapper.findIdAndMemberNameListByParentIdOfParentIdAndLevelId(parentId, levelId);
    }

    @Override
    public Long findCurDateCountMember() {
        return baseMapper.findCurDateCountMember();
    }

    @Override
    public Long findTotalMember() {
        return baseMapper.findTotalMember();
    }

    @Override
    public Boolean updateMemberSalt(Long memberId, String salt) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setSalt(salt);
        return update(memberEntity, "id = {0}", memberId);
    }

    @Override
    public Boolean updateMemberSecondarySalt(Long memberId, String salt) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setSecondarySalt(salt);
        return update(memberEntity, "id = {0}", memberId);
    }
}
